package conf

import (
	"github.com/Unknwon/goconfig"
	"github.com/cihub/seelog"
	"log"
	"sync"
)

var (
	ftpConfOnce     sync.Once
	ftp             Ftp
	dbConfOnce      sync.Once
	dbDir           string
	sendUrlConfOnce sync.Once
	sendUrl         string
	cronConfOnce    sync.Once
	cron            MyCron
	cfg             *goconfig.ConfigFile
)

func init() {
	var err error
	cfg, err = goconfig.LoadConfigFile("conf.ini")
	if err != nil {
		log.Fatalf("load conf.ini error : %v", err)
	}
}

type MyCron struct {
	ExectNotSuccessCron string
	DeleteFileCron      string
	FileMaxCount        int
	SubTime             int
}

type Ftp struct {
	Dir          string
	BackDir      string
	User         string
	Pass         string
	Port         int
	Host         string
	PublicIp     string
	PassivePorts string
	TLS          bool
	CertFile     string
	KeyFile      string
	ExplicitFTPS bool
}

func DbDir() string {
	var err error
	dbConfOnce.Do(func() {
		//创建链接Influxdb
		dbDir, err = cfg.GetValue("nutsdb", "dir")
		if err != nil {
			seelog.Error(err)
		}
	})
	return dbDir
}

func GetCron() MyCron {
	cronConfOnce.Do(func() {
		cron.ExectNotSuccessCron = cfg.MustValue("cron", "cron")
		cron.DeleteFileCron = cfg.MustValue("cron", "deletefilecron")
		cron.FileMaxCount = cfg.MustInt("cron", "fileMaxCount")
		cron.SubTime = cfg.MustInt("cron", "subTime")
	})
	return cron
}

func GetSenUrl() string {
	sendUrlConfOnce.Do(func() {
		sendUrl, _ = cfg.GetValue("", "sendurl")
	})
	return sendUrl
}

func FtpConf() *Ftp {
	ftpConfOnce.Do(func() {
		ftp.Dir = cfg.MustValue("ftp", "dir")
		ftp.BackDir = cfg.MustValue("ftp", "backDir")
		ftp.User = cfg.MustValue("ftp", "user", "admin")
		ftp.Pass = cfg.MustValue("ftp", "pass", "123456")
		ftp.Host = cfg.MustValue("ftp", "host", "0.0.0.0")
		ftp.PublicIp = cfg.MustValue("ftp", "publicIp", "")
		ftp.Port = cfg.MustInt("ftp", "port", 21)
		ftp.PassivePorts = cfg.MustValue("ftp", "passiveports", "1024-2047")
		ftp.TLS = cfg.MustBool("ftp", "tls", false)
		ftp.ExplicitFTPS = cfg.MustBool("ftp", "explicitFtps", false)
		ftp.CertFile = cfg.MustValue("ftp", "certfile", "")
		ftp.KeyFile = cfg.MustValue("ftp", "keyfile", "")

	})
	return &ftp
}
